package com.example.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.example.constant.EnumConstant.USER_STATE;


@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        httpServletResponse.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,X-App-Id, X-Token");
        httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");

        HttpSession session = request.getSession();
        log.info("SessionId:" + request.getSession().getId());
        String userAddress = (String) session.getAttribute(USER_STATE);

        if (null == userAddress) {
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置状态码为401（未授权）
            return false; // 阻止请求继续执行
        }
        return true; // 允许请求继续执行
    }
}

